package array;

import java.util.Arrays;

public class leetCode16_threeSumClosest {
    public int threeSumClosest(int[] nums, int target) {
        if(nums == null || nums.length == 0) return 0;
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length; i++) {
            int j = i + 1;
            int k = nums.length - 1;
            while (j < k){
                int sum = nums[i] + nums[j] + nums[k];
                if(Math.abs(sum - target) < Math.abs(ans - target)){
                    ans = sum;
                }
                if(sum > target){
                    k--;
                }else if (sum < target){
                    j++;
                }else{
                    return ans;
                }
            }

        }

        return ans;

    }
}
